
package com.example.sistemacompras;

import com.example.sistemacompras.db.DatabaseHandler;
import com.example.sistemacompras.entity.Person;
import com.example.sistemacompras.utils.Utils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SiginUserActivity extends Activity {

    private EditText nomeDeUsuarioU;

    private EditText EmailU;

    private Bitmap fotoU = null;

    private EditText passwordU;

    private TextView fotoTextView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sigin);
        nomeDeUsuarioU = (EditText) findViewById(R.id.nome_edit);
        nomeDeUsuarioU.setText("");
        EmailU = (EditText) findViewById(R.id.email_edit);
        EmailU.setText("");
        passwordU = (EditText) findViewById(R.id.password_edit);
        passwordU.setText("");
        fotoTextView = (TextView) findViewById(R.id.foto_text);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.cadastrar, menu);
        return true;
    }

    /*
     * (non-Javadoc)
     * @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        String nomeP = nomeDeUsuarioU.getText().toString();
        String emailP = EmailU.getText().toString();
        String passwordP = passwordU.getText().toString();
        Person person = new Person();
        person.setEmail(emailP);
        person.setName(nomeP);
        person.setPassword(passwordP);
        if (fotoU != null) {
            person.setPhoto(fotoU);
        }

        outState.putSerializable("user", person);
    }

    /*
     * (non-Javadoc)
     * @see android.app.Activity#onRestoreInstanceState(android.os.Bundle)
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onRestoreInstanceState(savedInstanceState);
        Person person = (Person) savedInstanceState.get("user");
        nomeDeUsuarioU.setText(person.getName());
        EmailU.setText(person.getEmail());
        fotoU = person.getPhoto();
        passwordU.setText(person.getPassword());
        ((ImageView) findViewById(R.id.user_photo)).setImageBitmap(fotoU);
    }

    public void cadastrarUsuario(View view) {
        String nomeP = nomeDeUsuarioU.getText().toString();
        String emailP = EmailU.getText().toString();
        String passwordP = passwordU.getText().toString();
        Person person = new Person();
        person.setEmail(emailP);
        person.setName(nomeP);
        person.setPassword(passwordP);
        if (fotoU != null) {
            person.setPhoto(fotoU);
        }

        boolean teste = DatabaseHandler.getInstance().createPerson(person);

        Intent returnIntent = new Intent();
        returnIntent.putExtra("cadastro", teste);
        setResult(RESULT_OK, returnIntent);
        finish();

    }

    // public void showFileChooser(View view) {
    // Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    // intent.setType("*/*");
    // intent.addCategory(Intent.CATEGORY_OPENABLE);
    //
    // try {
    // startActivityForResult(
    // Intent.createChooser(intent, "Select a File to Upload"),
    // FILE_SELECT_CODE);
    // } catch (android.content.ActivityNotFoundException ex) {
    // Toast.makeText(this, "Please install a File Manager.",
    // Toast.LENGTH_SHORT).show();
    // }
    // }
    //
    // @Override
    // protected void onActivityResult(int requestCode, int resultCode, Intent
    // data) {
    // switch (requestCode) {
    // case FILE_SELECT_CODE:
    // if (resultCode == RESULT_OK) {
    // Uri uri = data.getData();
    // String path = "";
    // try {
    // path = getPath(this, uri);
    // } catch (URISyntaxException e) {
    // e.printStackTrace();
    // }
    // fotoU = BitmapFactory.decodeFile(path);
    // fotoTextView.setText("Foto: "+path);
    // Log.d(TAG, "File Path: " + path);
    // }
    // break;
    // }
    // super.onActivityResult(requestCode, resultCode, data);
    // }
    String mCurrentPhotoPath;

    static final int REQUEST_TAKE_PHOTO = 1;

    @SuppressLint("SimpleDateFormat")
	private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(imageFileName, /* prefix */
                ".jpg", /* suffix */
                storageDir /* directory */
        );
        // Save a file: path for use with ACTION_VIEW intents
        try {
            mCurrentPhotoPath = getPath(this, Uri.parse(image.toURI().toString()));

        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        // fotoU = BitmapFactory.decodeFile(path);
        // fotoTextView.setText("Foto: "+path);
        // Log.d(TAG, "File Path: " + path);

        System.out.println("!!!!!!!!!!!!!!!!!!" + mCurrentPhotoPath);
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                // ...
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }

    public void shootPhoto(View view) {
        dispatchTakePictureIntent();

        fotoTextView.setText(mCurrentPhotoPath);
    }

    public void loadPhoto(View view) {
        Utils util = new Utils(this);
        int proportion = 6;
        int width = util.getWidthInPixels() / proportion;
        int height = util.getHeightInPixels() / proportion;

        fotoU = getResizedBitmap(BitmapFactory.decodeFile(mCurrentPhotoPath), width, height);

        ((ImageView) findViewById(R.id.user_photo)).setImageBitmap(fotoU);

    }

    public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

        int width = bm.getWidth();

        int height = bm.getHeight();

        float scaleWidth = ((float) newWidth) / width;

        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();

        matrix.postScale(scaleWidth, scaleHeight);
        matrix.postRotate(90.0f);

        Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);

        return resizedBitmap;

    }

    public static String getPath(Context context, Uri uri) throws URISyntaxException {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {
                "_data"
            };
            Cursor cursor = null;

            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {
                // Eat it
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public void enviarUsuario(View view) {
        String nome = String.valueOf(nomeDeUsuarioU.getText());
        String email = String.valueOf(EmailU.getText());
        String senha = String.valueOf(passwordU.getText());
        if ((nome != null && nome != "") && (email != null && email != "")
                && (senha != null && senha != "")) {
            EditText number = (EditText) findViewById(R.id.phone_number);
            String sms = "cadastro;" + nome + ";" + email + ";" + senha;
            Intent smsIntent = new Intent(Intent.ACTION_VIEW);
            smsIntent.setType("vnd.android-dir/mms-sms");
            smsIntent.putExtra("address", String.valueOf(number.getText()));
            smsIntent.putExtra("sms_body", sms);
            startActivity(smsIntent);
        }
    }
}
